How to use group by in LINQ C# and fetch the list of records?
How to use group by in LINQ C# and fetch the list of records?
402
17-Aug-2023
Aryan Kumar
18-Aug-2023Sure, I can help you with that.
The
GroupBy()method in LINQ is used to group elements in a sequence based on a common property. TheGroupBy()method returns aIGrouping<TKey, TResult>object, which is a collection of elements that have the same key.To use the
GroupBy()method, you need to specify the property that you want to group the elements by. You can also specify a lambda expression to customize the grouping.The following code groups a list of
Personobjects by their age:C#
In this code, the
GroupBy()method groups thepeoplelist by theAgeproperty of thePersonobjects. ThegroupedPeoplevariable is aIGrouping<int, Person>object, which is a collection ofPersonobjects that have the same age.To fetch the list of records, you can use the
ToList()method. TheToList()method returns a list of all the elements in theIGroupingobject.The following code fetches the list of records from the
groupedPeoplevariable:C#
In this code, the
recordsvariable is a list of all thePersonobjects in thegroupedPeopleobject.